<template>
  <view>
    <view class="switch-config" v-if="modal === 'cell'">
      开启手动控制，进入库存盘点
      <m-button shape="round" background="#F55822" size="md" width="158rpx" @click="handleClick">
        {{ openManualControl === 0 ? '立即开启' : '立即关闭' }}
      </m-button>
    </view>

    <view v-else class="switch-button">
      <m-switch :value="!!value" active-text="关闭" inactive-text="打开" @change="handleClick" />
      <text>手动控制</text>
    </view>
  </view>
</template>

<script>
import { listConfig, updateConfig } from '@/api/modules/inventory'
import { minCache } from '@/utils/min-cache'

export default {
  props: {
    value: {
      type: Number,
      default: 1,
    },
    modal: {
      type: String,
      default: 'cell',
    },
  },
  data() {
    return {
      openManualControl: 1,
      form: {
        password: '',
      },
      show: false,
      rules: {
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: ['change', 'blur'],
          },
        ],
      },
      fun: null,
      info: {},
    }
  },
  async mounted() {
    this.fetchData()
  },
  methods: {
    async fetchData() {
      const { rows } = await listConfig({ configKey: 'openManualControl' })
      this.openManualControl = +rows[0].configValue
      this.$emit('input', this.openManualControl)
      if (this.openManualControl === 1) {
        minCache.set('firstInventorySwitch', 1)
      }

      return rows[0]
    },
    close(e) {
      this.fun = e
      this.handleClick()
    },
    async handleClick() {
      try {
        const data = await this.fetchData()
        await updateConfig({
          ...data,
          configKey: 'openManualControl',
          configValue: this.openManualControl === 0 ? 1 : 0,
        })

        await this.fetchData()
        if (this.openManualControl === 0) {
          this.fun && this.fun()
        }
      } catch (e) {}
    },
  },
}
</script>

<style lang="scss" scoped>
.switch-config {
  position: fixed;
  bottom: 120rpx;
  margin: 0 20rpx;
  padding: 20rpx;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.68);
  border-radius: 12rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #fff;
  overflow: hidden;
}

.switch-button {
  display: flex;
  flex-direction: column;
  color: #56718c;
  font-size: 24rpx;
  text-align: center;
  text {
    margin-top: 10rpx;
  }
}
</style>
